package edu.hubu.book.service.impl;

import edu.hubu.book.dao.SearchDao;
import edu.hubu.book.domain.Book;
import edu.hubu.book.domain.ExtendBook;
import edu.hubu.book.domain.Page;
import edu.hubu.book.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author waxijiang
 */
@Service("searchService")
public class SearchServiceImpl implements SearchService {

    final SearchDao searchDao;

    public SearchServiceImpl(SearchDao searchDao) {
        this.searchDao = searchDao;
    }

    @Override
    public Integer findIdByFirstClassName(String firstClassName) {
        return searchDao.findIdByFirstClassName(firstClassName);
    }

    @Override
    public Integer findIdBySecondClassName(String secondClassName) {
        return searchDao.findIdBySecondClassName(secondClassName);
    }

    @Override
    public Page findByPage(Integer currentPage, Integer pageSize, String bookName, Integer sid, Integer ssid) {
        // 分页查询
        List<Book> books = searchDao.findByPage((currentPage - 1) * pageSize, pageSize, bookName, sid, ssid);
        int resultCount = searchDao.getSearchCount(bookName, sid, ssid);
        // 拿到总页数
        int totalPage = (int) Math.ceil(resultCount / (float) pageSize);
        List<ExtendBook> extendBooks = new ArrayList<>();
        // 通过book构建extendBook
        for (Book book : books) {
            String firstClassName = searchDao.findFirstClassNameById(book.getSid());
            String secondClassName = searchDao.findSecondClassNameById(book.getSsid());
            ExtendBook extendBook = new ExtendBook(book.getBid(), book.getBookName(), book.getImgUrl(), book.getPrice(), book.getDiscount(), book.getAuthor(), book.getPublishingHouse(), book.getSid(), book.getSsid(), book.getDescription(), firstClassName, secondClassName);
            extendBooks.add(extendBook);
        }
        // 封装查询结果
        return new Page(pageSize, currentPage, extendBooks, totalPage, resultCount);
    }

    @Override
    public List<String> getAllFirstClass() {
        return searchDao.findAllFirstClass();
    }

    @Override
    public List<String> getSecondClass(Integer sid) {
        return searchDao.findAllSecondClassByFirstClassId(sid);
    }
}
